<?php

/*
 * This file is part of the overtrue/easy-sms.
 *
 * (c) overtrue <i@overtrue.me>
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

namespace End01here\EasySms\Gateways;


use End01here\EasySms\Contracts\MessageInterface;
use End01here\EasySms\Contracts\PhoneNumberInterface;
use End01here\EasySms\Exceptions\GatewayErrorException;
use End01here\EasySms\Traits\HasHttpRequest;

/**
 * Class AliyunGateway.
 *
 * @author carson <docxcn@gmail.com>
 *
 * @see https://help.aliyun.com/document_detail/55451.html
 */
class KewailGateway extends Gateway
{
    use HasHttpRequest;

    const ENDPOINT_URL = 'https://live2.moduyun.com/sms/v2/sendsinglesms';

    const ENDPOINT_TYPE = '0';

    public function send(PhoneNumberInterface $to, MessageInterface $message )
    {
        $random=$this->getRandom();
        //生成请求地址
        $wholeUrl = self::ENDPOINT_URL . "?accesskey=" . $this->config['kewail']['accesskey'] . "&random=" . $random;
        //获取签名

        //组装请求数据
        $curTime = time();
        $data = new \stdClass();
        $tel = new \stdClass();
        $tel->nationcode = "" . $to->getIDDCode();
        $tel->mobile = "" . $to->getNumber();
        $data->tel = $tel;
        $data->templateId = $message->getTemplate();
        $data->parameter = $message->getData();
        $data->signId =  $this->config['sign_text'];
        $data->time = $curTime;
        $data->extend = '';
        $data->ext = '';
        //生成签名数据
        $data->sig = hash("sha256",
            "secretkey=".$this->config['kewail']['secretkey']."&random=".$random."&time=".$curTime."&mobile=".$tel->mobile, FALSE);
        //发起请求
        $result = $this->postJson($wholeUrl, json_encode($data));
        //解析返回信息sadasdsfdsf
        if (empty($result['sid'])) {
            if(empty($result)){
                throw new GatewayErrorException('短信发送失败', 0, $result);
            }else{
                throw new GatewayErrorException($result['errmsg'], $result['result'], $result);
            }
        }

        return ['code'=>'1','msg'=>'短信发送成功'];
    }

    /**
     * 生成随机出
     * @return int
     */
    private function getRandom()
    {
        return rand(100000, 999999);
    }


}
